package cn.edu.zstu.overlappingdisappear.sqlite;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

import cn.edu.zstu.overlappingdisappear.bean.LeverBean;

/**
 * @Author ZhuMingWei(986990501@qq.com)
 * @Date on 2019/11/15
 * @Version v1.0.0
 * @Company TODO
 * @Describle TODO
 */

public class ChainDao {

    private SQLiteDatabase db;
    private DBHelper mDBHelper;

    public ChainDao(Context context) {
        mDBHelper = new DBHelper(context);
        db = mDBHelper.getWritableDatabase();
    }

    public void close() {
        if (db != null) {
            db.close();
            db = null;
        }
    }

    public void updateRecord(int difficult,int level,int record) {
        String sql = "update tb_chain set RECORD = "+record+" where DIFFICULT = "+difficult+" and LEVER" +
                "" +
                " = "+level;
        db.execSQL(sql);
    }

    public List<LeverBean> queryLevers(int difficult) {
        String sql = "select * from tb_chain where DIFFICULT = ? order by LEVER";
        Cursor c = db.rawQuery(sql, new String[]{String.valueOf(difficult)});
        List<LeverBean> levers = new ArrayList<>();
        while (c.moveToNext()){
            LeverBean leverBean = new LeverBean();
            leverBean.ID = c.getInt(c.getColumnIndex("ID"));
            leverBean.DIFFICULT = c.getInt(c.getColumnIndex("DIFFICULT"));
            leverBean.LEVER = c.getInt(c.getColumnIndex("LEVER"));
            leverBean.INIT_STATE = c.getString(c.getColumnIndex("INIT_STATE"));
            leverBean.GOAL_STATE = c.getString(c.getColumnIndex("GOAL_STATE"));
            leverBean.RECORD = c.getInt(c.getColumnIndex("RECORD"));
            levers.add(leverBean);
        }
        c.close();
        return levers;
    }

    public LeverBean queryLevel(int difficult, int level) {
        String sql = "select * from tb_chain where DIFFICULT = ? and LEVER = ?";

        Cursor c = db.rawQuery(sql, new String[]{String.valueOf(difficult),String.valueOf(level)});
        LeverBean leverBean = null;
        while (c.moveToNext()){
            leverBean = new LeverBean();
            leverBean.ID = c.getInt(c.getColumnIndex("ID"));
            leverBean.DIFFICULT = c.getInt(c.getColumnIndex("DIFFICULT"));
            leverBean.LEVER = c.getInt(c.getColumnIndex("LEVER"));
            leverBean.INIT_STATE = c.getString(c.getColumnIndex("INIT_STATE"));
            leverBean.GOAL_STATE = c.getString(c.getColumnIndex("GOAL_STATE"));
            leverBean.RECORD = c.getInt(c.getColumnIndex("RECORD"));
        }
        c.close();
        return leverBean;
    }
}
